<template>
	<z-paging ref="paging" :refresher-out-rate="0.8" :show-empty-view-reload-when-error="false"
		:empty-view-img-style="{ width: '308rpx', height: '308rpx' }"
		empty-view-error-img="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/12/1c53b8aed0c74201bb092265803a1d48.png"
		empty-view-img="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/12/987eadb1d50949a0a7e25dbbd99abe30.png"
		empty-view-error-text="暂无数据" safe-area-inset-bottom bg-color="#F5F8FE" v-model="dataList" @query="queryList">
		<view slot="top" class="topTabbar">
			<u-tabs :current="currentTab" :list="tabList" @change="tabChange" :scrollable="false"></u-tabs>
		</view>
		<view class="cellBox">
			<view class="flex_wrap fileBox" v-if="currentTab == 0"><u-icon label="创建优惠券" size="28rpx" name="plus" color="#777"
					labelColor="#777" @click="to_createCoupon()"></u-icon></view>
			<view class="createDetail" v-for="(item, index) in dataList" :key="index" v-if="currentTab == 0">
				<view class="flex_wrap row_between">
					<view class="flex_wrap">
						<view>
							<u-text :text="'已领取 ' + item.claimedQuantity + ' 张'" size="28rpx" color="#3D3D3D " />
						</view>
						<u-text :text="'已核销 ' + item.useNumber + ' 张'" size="28rpx" color="#3D3D3D " margin="0 16rpx"/>
					</view>
					<u-text :text="'总数 ' + item.favorableNum + ' 张'" size="28rpx" align="right" color="#3D3D3D " />
				</view>
				<u-line dashed color="#CCCCCC" margin="24rpx 0" />
				<!-- 列表 -->
				<view class="createList flex_wrap row_between row_middle"
					@click="to_claimedQuantity(item.id)">
					<view class="flex_wrap row_middle">
						<u-icon
							name="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/25/c61f6633bd394bfba8c1ab7c545a3dee.png"
							size="124rpx" />
						<view>
							<u-text :text="item.favorableTitle" lines="2" size="32rpx" color="#FF3C3C " margin="0 16rpx" />
							<u-text text="无门槛" size="24rpx" color="#3D3D3D" margin="8rpx 16rpx" />
							<u-text :text="`有效期限至` +  $u.timeFormat(item.useTimeEnd, 'yyyy-mm-dd')" size="24rpx" color="#666 " margin="0 16rpx" />
						</view>
					</view>
				</view>
				<!-- 按钮部分  -->
				<u-line dashed color="#CCCCCC" />
				<view class="btnBox flex_wrap row_around row_middle">
						<u-text prefixIcon="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/customer/album/2024/03/15/4e385c14ca754c10b7fcbc83a3bc3fcc.png" iconStyle="width:36rpx;height:36rpx;margin-right:6rpx;" text="领券" color="#3D3D3D" size="32rpx" align="right"  @click="to_operate(item)"/>
						<u-text prefixIcon="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/customer/album/2024/03/15/12b4059c5afc409781fa2bf1ae0bdf00.png" iconStyle="width:36rpx;height:36rpx;margin-right:6rpx;" text="编辑" color="#3D3D3D" size="32rpx" align="right" @click="to_editCoupon(item.id)" />
						<u-text prefixIcon="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/customer/album/2024/03/15/dfc425cbae49442aba4089cf1f179497.png" iconStyle="width:36rpx;height:36rpx;margin-right:6rpx;" text="删除" color="#3D3D3D" size="32rpx" align="right" @click="del(item.id)"/>
				</view>
			</view>
			<!-- 记录列表 -->
			<view class="detail" v-for="(item, index) in dataList" :key="index" v-if="currentTab == 1">
				<view class="detail_title">
					<view class="flex_wrap">
						<view style="width: 348rpx;">
							<u-text
								prefixIcon="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/25/c61f6633bd394bfba8c1ab7c545a3dee.png"
								iconStyle="margin-right:16rpx;width:56rpx;height:56rpx" size="36rpx" color="#333" bold
								:text="item.title" lines="1" />
						</view>
						<u-text v-if="item.total > item.takeNumber" text="撤回" size="32rpx" color="#FF3C3C " margin="0 0 0 20rpx" @click="withdraw(item.uniqueId)"/>
					</view>
					<u-line dashed color="#CCCCCC" margin="20rpx 0 28rpx" />
					<view class="flex_wrap row_between row_middle">
						<view>
							<view class="flex_wrap">
								<view class="">
									<u-text color="#777" size="28rpx" :text="'印刷数量：'+ item.total" />		
								</view>
								<u-text color="#DCB210" size="28rpx" :text="'已领：'+ item.takeNumber" margin="0 32rpx" />
							</view>
							<u-text v-if="item.type == '2'" color="#777" size="28rpx" :text="'转发渠道：'+ item.channelUserName" margin="18rpx 0 0" />
							<u-text v-if="item.type == '4'" color="#777" size="28rpx" :text="'开始时间：'+ $u.timeFormat(item.startTime, 'yyyy-mm-dd')" margin="18rpx 0 0" />
							<u-text color="#777" size="28rpx" :text="item.type == '4' ? ('结束时间：'+$u.timeFormat(item.endTime, 'yyyy-mm-dd')) : ('转发时间：'+ $u.timeFormat(item.createTime, 'yyyy-mm-dd'))" margin="18rpx 0 0" />
						</view>
						<view v-if="currentTab == '1' && (item.type=='4' || item.type=='1')" @click="qrCode(item)">
							<u-image height="100rpx" width="100rpx"
								src="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/01/10/87f38641d0a6454e8478b0f20c8398a7.png" mode="aspectFill" />
						</view>
					</view>
					<view class="cardbgs" v-if="currentTab == '1'" :style="{ background: statusBg[item.type] }">
						{{statusTitle[item.type]}}</view>
				</view>
			</view>
			<u-action-sheet :actions="actionList" @select="selectClick" :closeOnClickOverlay="true" :closeOnClickAction="true" @close="actionShow=false" :show="actionShow" cancelText="取消"></u-action-sheet>
			<u-modal :show="show" ref="editModal" title="发给渠道" showCancelButton @confirm="confirmEdit"
				@cancel="cancelEdit" confirmText="下一步" confirmColor="#1682FF">
				<view slot="default" style="width: 100%">
					<u--text text="转发人手机号" size="32rpx" color="#3D3D3D" lineHeight="80rpx"></u--text>
					<u--input type="number" placeholder="请输入手机号" :maxlength="11" clearable v-model="phoneNum"
						:customStyle="{
			                            background: '#F7F7F7',
			                            borderRadius: '16rpx 16rpx 16rpx 16rpx',
			                            border: 'none',
			                            height: '80rpx',
			                        }" :placeholderStyle="{
			                            fontSize: '28rpx',
			                            color: '#F7F7F7',
			                        }"></u--input>
				</view>
			</u-modal>
			<u-modal
			    :show="show1"
			    ref="editModal"
			    title="发给渠道"
			    showCancelButton
			    @confirm="confirmEdit1"
			    @cancel="cancelEdit1"
			    confirmText="确定"
			    confirmColor="#1682FF"
			    cancelText="上一步"
			>
			    <view slot="default" style="width: 100%">
			        <u--text
			            text="转发用户"
			            size="32rpx"
			            color="#3D3D3D"
			            lineHeight="80rpx"
			        ></u--text>
			        <u--input
			            v-model="userNamePhone"
			            disabled
			            :customStyle="{
			                background: '#F7F7F7',
			                borderRadius: '16rpx 16rpx 16rpx 16rpx',
			                border: 'none',
			                height: '80rpx',
			            }"
			            :placeholderStyle="{
			                fontSize: '28rpx',
			                color: '#F7F7F7',
			            }"
			        ></u--input>
			        <u--text
			            text="转发数量"
			            size="32rpx"
			            color="#3D3D3D"
			            lineHeight="80rpx"
			        ></u--text>
			        <u--input
			            type="number"
			            placeholder="请输入转发数量"
			            :maxlength="11"
			            clearable
			            v-model="numBer"
			            :customStyle="{
			                background: '#F7F7F7',
			                borderRadius: '16rpx 16rpx 16rpx 16rpx',
			                border: 'none',
			                height: '80rpx',
			            }"
			            :placeholderStyle="{
			                fontSize: '28rpx',
			                color: '#F7F7F7',
			            }"
			        ></u--input>
			    </view>
			</u-modal>
			
			<u-modal :show="shareShow" ref="editModal" :title="btnTypes == 1 ? '发红包数量' : '请输入优惠券数量' " showCancelButton @confirm="shareConfirmEdit" @cancel="shareCancelEdit"
				confirmColor="#1682FF">
				<view slot="default" style="width: 100%">
					<u--text :text="btnTypes == 1 ? '发红包数量' :'优惠券数量' " size="32rpx" color="#3D3D3D" lineHeight="80rpx"></u--text>
					<u--input type="number" :placeholder="btnTypes == 1 ? '请输入发红包数量' :'请输入优惠券数量' " clearable v-model="couponNum" :customStyle="{
			                background: '#F7F7F7',
			                borderRadius: '16rpx 16rpx 16rpx 16rpx',
			                border: 'none',
			                height: '80rpx',
			            }" :placeholderStyle="{
			                fontSize: '28rpx',
			                color: '#F7F7F7',
			            }"></u--input>
					<u-gap height="32rpx" bgColor="#fff" v-if="btnTypes == '1'" />
					<view class="flex_wrap row_between" v-if="btnTypes == '1'">
					    <u--text text="用户限领取一张" color="#3D3D3D" size="32rpx" />
					    <view class="flex_wrap">
					        <u-switch
					            iconPlacement="right"
					            v-model="checkedOnline"
					            :activeValue="1"
					            :inactiveValue="0"
					        ></u-switch>
					    </view>
					</view>
				</view>
			</u-modal>
			<!-- 线上活动 -->
			<u-modal :show="onlineShow" ref="editModal" title="线上活动" showCancelButton @confirm="onlineConfirm"
				@cancel="onlineEdit" confirmText="确定" confirmColor="#1682FF">
				<view slot="default" style="width: 100%">
					<u--text text="开始时间" size="32rpx" color="#3D3D3D" lineHeight="80rpx"></u--text>
					<view class="timeBox">
						<u-text @click="pickerShow = true" :color="startSubmitTime ? '#303133' : '#aaa'" size="30rpx"
							:text="
						        startSubmitTime
						            ? startSubmitTime
						            : '请选择开始时间'
						    " />
					</view>
					<u--text text="结束时间" size="32rpx" color="#3D3D3D" lineHeight="80rpx"></u--text>
					<view class="timeBox">
						<u-text @click="pickerShow2 = true" :color="endSubmitTime ? '#303133' : '#aaa'" size="30rpx"
							:text="
						        endSubmitTime
						            ? endSubmitTime
						            : '请选择结束时间'
						    " />
					</view>
					<u--text text="活动数量" size="32rpx" color="#3D3D3D" lineHeight="80rpx"></u--text>
					<u--input type="number" placeholder="请输入活动数量" clearable v-model="onlineNum" :customStyle="{
			                            background: '#F7F7F7',
			                            borderRadius: '16rpx 16rpx 16rpx 16rpx',
			                            border: 'none',
			                            height: '80rpx',
			                        }" :placeholderStyle="{
			                            fontSize: '28rpx',
			                            color: '#aaa',
			                        }"></u--input>
				</view>
			</u-modal>
			<u-popup :show="qrShow" @close="qrShow =false" mode="center" closeable @open="open">
				<view class="qrBox">
					<u-image
						:src="baseSrc"
						width="320rpx" height="320rpx" mode="widthFix" />
					<u-text color="#777" size="28rpx" text="长按二维码识别|下载|分享" margin="36rpx 0 0" align="center" />
				</view>
			</u-popup>
			<u-datetime-picker :show="pickerShow" mode="datetime" v-model="startTime" @confirm="startTimeChange"
				@cancel="pickerShow = false"></u-datetime-picker>
			<u-datetime-picker :show="pickerShow2" mode="datetime" v-model="endTime" @confirm="endTimeChange"
				@cancel="pickerShow2 = false"></u-datetime-picker>
		</view>
	</z-paging>
</template>

<script>
	import {
		addAgentAssociatedWithEquityCard,
		queryAgentAssociatedWithEquityCard,
		queryStatisticalDataWithEquityCard,
		getSalesmanByPhone,
		genWxMpQrCode,
	} from "@/api/cardSalesman";
	import {
		favorableList,
		favorableLog,
		getProviderFavorable,
		getTransferList,
		createActivity,
	} from "@/api/coupon.js";
	import {
		viewOneselfShareFavorable,
		createCouponList,
		deleteCoupon,
		favorableActivityList,
		getMiniCodeByAppId,
		cancelActivity
	} from "@/api/order.js";
	import moment from "moment";
	const dayStart = moment(
		new Date(new Date(new Date().toLocaleDateString()).getTime())
	);
	const dataEnd = moment(
		new Date(
			new Date(new Date().toLocaleDateString()).getTime() +
			24 * 60 * 60 * 1000 -
			1
		)
	);
	import {
		mapGetters
	} from "vuex";
	let customerId = "";
	export default {
		data() {
			return {
				appId: this.$appId,
				tabList: [{
						name: "我创建的",
						id: 0,
					},
					{
						name: "优惠券记录",
						id: 1,
					},
				],
				currentTab: 0,
				dataList: [],
				statusBg: {
					1: "#A3ACE4",
					2: "#78C997",
					3: "#F1CF8F",
					4: "#EFB791",
				},
				statusTitle: {
					1: "转发微信",
					2: "发给渠道",
					3: "发红包",
					4:"线上活动",
				},
				show: false,
				show1: false,
				actionShow: false,
				shareShow: false,
				onlineShow: false,
				phoneNum: "",
				numBer: "",
				userNamePhone:'',
				actionList:[
					{
						type:'1',
						name:'转发微信'
					},
					{
						type:'2',
						name: '当面发'
					},
					{
						type:'3',
						name: '发给渠道'
					},
					{
						type:'4',
						name: '线上活动'
					}
				],
				couponNum:'',
				idS:'',
				btnTypes:'',
				startPicker: "",
				startSubmitTime: '',
				endSubmitTime: '',
				startTime: dayStart,
				endTime: dataEnd,
				pickerShow: false,
				pickerShow2: false,
				onlineNum: '',
				baseSrc:'',
				qrShow: false,
				nowCountNum:'',
				checkedOnline: 0,
			};
		},
		onShareAppMessage(res) {
			  return {
				title: '微信小程序测试分享',
			  }
		},
		methods: {
			withdraw(uniqueId){
				const that = this;
				uni.showModal({
				    title: "",
				    content: "确定要撤回此优惠券吗？",
				    success({ confirm, cancel }) {
				        if (confirm) {
				            cancelActivity(uniqueId).then((res) => {
				                uni.$u.toast("撤回成功！");
								that.$refs.paging.reload();
				            });
				        }
				    },
				});
			},
			qrCode(item){
				const params = {
				   page: "pages_coupon/receive/index",
				   scene:item.uniqueId,
				   env_version: __wxConfig.envVersion,
				   check_path: false,
				   appId: this.appId,
				};
				getMiniCodeByAppId(params).then((res) => {
					if (res.code === 200 && res.data) {
					   var showImgData = res.data;
					   this.baseSrc = "data:image/png;base64," + showImgData;
					   this.qrShow = true
					}
				});
			},
			
			selectClick(e){
				console.log(e)
				this.actionShow = false;
				if(e.type == '3') return this.show = true;
				if(e.type == '1' || e.type == '2') {
					this.btnTypes = e.type
					 console.log(this.btnTypes,'this.btnTypes>>')
					this.shareShow = true;
					return
				} 
				if (e.type == '4') return this.onlineShow = true;
			},
			// 线上活动
			onlineEdit() {
				this.onlineNum = "";
				this.onlineShow = false;
			},
			async onlineConfirm() {
				if (!this.startSubmitTime.length)
					return uni.showToast({
						title: "请选择开始时间",
						icon: "none",
					});
				if (!this.endSubmitTime.length)
					return uni.showToast({
						title: "请选择结束时间",
						icon: "none",
					});
				if (!this.onlineNum.trim().length || !/^[0-9]*$/.test(this.onlineNum))
					return uni.showToast({
						title: "请输入数量",
						icon: "none",
					});
				if (Number(this.onlineNum) > Number(this.nowCountNum)) return uni.showToast({
					title: "请输入正确数量",
					icon: "none",
				});
				const params = {
					favorableId: this.idS,
					number: this.onlineNum,
					type: 4,
					endTime: this.endSubmitTime,
					startTime: this.startSubmitTime
				};
				let res = await createActivity(params);
				if (res.code === 200) {
					uni.$u.toast('创建线上活动成功');
					this.onlineEdit();
					this.$refs.paging.reload();
				}
			},
			startTimeChange(e) {
				const time =
					typeof e.value === "number" ? e.value : Date.parse(e.value);
				this.startSubmitTime = moment(time).format(
					"YYYY-MM-DD HH:mm:ss"
				);
				this.pickerShow = false;
			},
			endTimeChange(e) {
				const time =
					typeof e.value === "number" ? e.value : Date.parse(e.value);
				this.endSubmitTime = moment(time).format(
					"YYYY-MM-DD HH:mm:ss"
				);
				this.pickerShow2 = false;
			},
			
			
			cancelEdit() {
			    this.phoneNum = "";
			    this.show = false;
			},
			cancelEdit1() {
			    this.show1 = false;
			    this.numBer = "";
			},
			async confirmEdit() {
			    if (
			        !this.phoneNum.trim().length ||
			        !/^1[3456789]\d{9}$/.test(this.phoneNum)
			    )
			        return uni.showToast({
			            title: "请输入正确的手机号",
			            icon: "none",
			        });
			    let { code, data } = await getSalesmanByPhone({
			        phone: this.phoneNum,
			    });
			    if (code === 200 && data) {
			        console.log("data :>> ", data);
			        customerId = data.id;
			        this.userNamePhone = `${data?.salesmanName ?? "微信用户"}  ${
			            data.mobile
			        }`;
			        this.show1 = true;
			    } else {
			        uni.showToast({
			            title: "请输入正确的渠道手机号",
			            icon: "none",
			        });
			    }
			},
			async confirmEdit1() {
				if (!this.numBer.trim().length || !/^[0-9]*$/.test(this.numBer))
					return uni.showToast({
						title: "请输入数量",
						icon: "none",
					});
				if (Number(this.numBer) > Number(this.nowCountNum)) return uni.showToast({
					title: "请输入正确数量",
					icon: "none",
				});
				this.show1 = true;
				this.show = true;
				const params = {
					favorableId: this.idS,
					channelUserMobile: this.phoneNum,
					number: this.numBer,
					type:2 //渠道
				};
				let res = await createActivity(params);
				if (res.code === 200) {
					uni.$u.toast('发送成功');
					this.cancelEdit();
					this.cancelEdit1();
					this.$refs.paging.reload();
				}
			},
			to_operate(item) {
				// 假设过期时间是一个字符串，格式为YYYY-MM-DD HH:mm:ss
				const expireTimeStr = item.useTimeEnd;
				// 将过期时间字符串转换为Date对象
				const expireTime = new Date(expireTimeStr);
				// 获取当前时间
				const currentTime = new Date();
				// 比较过期时间是否小于（即早于）当前时间
				if (expireTime < currentTime) {
				  uni.$u.toast("不好意思，该优惠券已过期！");
				} else {
				  this.idS = item.id;
				  this.nowCountNum = item.surplusCount;
				  this.actionShow = true;
				}
			},
			async tabChange(e) {
				this.currentTab = e.index;
				await this.$refs.paging.reload();
			},
			async queryList(pageNo, pageSize) {
				const that = this;
				const params = {
					pageNum: pageNo,
					pageSize: pageSize,
				};
				let result;
				switch (this.currentTab) {
					case 0:
						result = await createCouponList(params);
						break;
					case 1:
						result = await favorableActivityList(params);
						break;
					default:
						result = await createCouponList(params);
				}
				that.$refs.paging.completeByTotal(result.data.rows, result.data.total);
			},
			to_createCoupon(){
				uni.navigateTo({
				    url: "/pages_coupon/create/index",
				});
			},
			to_editCoupon(id){
				this.$u.route({
					url: "/pages_coupon/create/index",
					params: {
						id,
						type :'编辑',
					},
				});
			},
			del(id) {
			    const that = this;
			    uni.showModal({
			        title: "",
			        content: "确定要删除此优惠券吗？",
			        success({ confirm, cancel }) {
			            if (confirm) {
			                deleteCoupon(id).then((res) => {
			                    uni.$u.toast("删除成功！");
								that.$refs.paging.reload();
			                });
			            }
			        },
			    });
			},
			shareCancelEdit() {
				this.couponNum = "";
				this.shareShow = false;
			},
			async shareConfirmEdit() {
				if (!this.couponNum) return uni.showToast({
					title: "请输入数量",
					icon: "none",
				});
				if (Number(this.couponNum) > Number(this.nowCountNum)) return uni.showToast({
					title: "请输入正确数量",
					icon: "none",
				});
				this.shareShow = false;
				if(this.btnTypes == 1){
					uni.$u.route({
						url: "/pages_coupon/shareDetail/index",
						params: {
							couponNum: this.couponNum,
							ledId: this.idS,
							btnTypes: this.btnTypes,
							checkedOnline:this.checkedOnline
						},
					});
				}else{
					await createActivity({
					   favorableId: this.idS,
					   number: this.couponNum,
					   type: 1,
					})
					    .then(async (res) => {
					        this.receiveId = res.data.uniqueId
							console.log(res,this.receiveId,'this.receiveId>>>')
							uni.$u.route({
								url: "/pages_coupon/faceReceive/index",
								params: {
									couponNum: this.couponNum,
									ledId: this.idS,
									uniqueId:this.receiveId
								},
							});
					    })
					    .catch((error) => {
					        uni.$u.toast(error);
					    });
				}
			},
		},
	};
</script>

<style lang="scss" scoped>
	.topTabbar {
		background-color: #fff;
		padding-bottom: 16rpx;
	}

	.cellBox {
		width: 92vw;
		margin: 0 auto;

		::v-deep .u-cell {
			box-shadow: 0 0 12rpx 2rpx rgba(0, 0, 0, 0.08);
			margin-top: 32rpx;
			border-radius: 20upx;
		}

		::v-deep .u-cell__body {}
	}

	.fileBox {
		justify-content: flex-end;
		padding: 30rpx 20rpx 0 0;
	}

	.detail {
		width: 100%;
		box-sizing: border-box;
		border-radius: 20rpx;
		margin-top: 32rpx;
		background: #ffffff;

		&_title {
			width: 100%;
			padding: 26rpx 28rpx;
			box-sizing: border-box;
			position: relative;
		}
	}

	.cardbgs {
		position: absolute;
		top: 26rpx;
		right: 0rpx;
		padding: 0 30rpx;
		border-radius: 28rpx 0 0 28rpx;
		height: 56rpx;
		text-align: center;
		line-height: 56rpx;
		font-size: 36rpx;
		color: #fff;
	}
	.createDetail {
		width: 100%;
		box-sizing: border-box;
		border-radius: 20rpx;
		margin-top: 32rpx;
		background: #ffffff;
		padding: 36rpx 32rpx 0;
		position: relative;
	}
	.createList {
		padding-bottom: 30rpx;
		position: relative;
	}
	.btnBox {
		height: 72rpx;
		width: 100%;padding-left:80rpx ;
	}
	.timeBox {
		background: #F7F7F7;
		border-radius: 16rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		padding-left: 20rpx;
	}
.qrBox{
		padding: 100rpx 60rpx 20rpx;
	}
</style>